import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../stores/chat_store.dart';
import '../widgets/avatar_widget.dart';

// 聊天详情页面
class ChatDetailScreen extends StatefulWidget {
  const ChatDetailScreen({Key? key}) : super(key: key);

  @override
  State<ChatDetailScreen> createState() => _ChatDetailScreenState();
}

class _ChatDetailScreenState extends State<ChatDetailScreen> {
  // 消息输入框控制器
  final TextEditingController _messageController = TextEditingController();
  // 滚动控制器
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  // 滚动到列表底部
  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final chatStore = Provider.of<ChatStore>(context);

    // 在构建完成后滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());

    return Observer(
      builder: (_) {
        final currentChat = chatStore.currentChatItem;

        return Scaffold(
          appBar: AppBar(
            title: currentChat != null
                ? Row(
                    children: [
                      AvatarWidget(
                        imageUrl: currentChat.avatar,
                        size: 36,
                        isOnline: currentChat.isOnline,
                      ),
                      const SizedBox(width: 8),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(currentChat.name),
                          if (currentChat.isOnline)
                            const Text(
                              '在线',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.green,
                              ),
                            ),
                        ],
                      ),
                    ],
                  )
                : const Text('聊天'),
            actions: [
              IconButton(
                icon: const Icon(Icons.more_vert),
                onPressed: () {
                  // TODO: 显示更多选项菜单
                },
              ),
            ],
          ),
          // 聊天内容区域
          body: Column(
            children: [
              // 消息列表
              Expanded(
                child: Observer(
                  builder: (_) {
                    final messages = chatStore.currentMessages;

                    if (messages.isEmpty) {
                      return const Center(child: Text('暂无消息记录'));
                    }

                    return ListView.builder(
                      controller: _scrollController,
                      padding: const EdgeInsets.all(16),
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        final message = messages[index];
                        final previousMessage = index > 0
                            ? messages[index - 1]
                            : null;

                        // 判断是否需要显示时间分割线
                        final showTimeDivider =
                            previousMessage == null ||
                            _shouldShowTimeDivider(
                              previousMessage.timestamp,
                              message.timestamp,
                            );

                        return Column(
                          children: [
                            // 时间分割线
                            if (showTimeDivider)
                              _buildTimeDivider(message.timestamp),

                            // 消息气泡
                            MessageBubble(message: message, isMe: message.isMe),
                          ],
                        );
                      },
                    );
                  },
                ),
              ),

              // 消息输入区域
              Container(
                padding: const EdgeInsets.all(8.0),
                decoration: BoxDecoration(
                  color: Theme.of(context).scaffoldBackgroundColor,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 5,
                      offset: const Offset(0, -1),
                    ),
                  ],
                ),
                child: Row(
                  children: [
                    // 添加附件按钮
                    IconButton(
                      icon: const Icon(Icons.add_circle_outline),
                      onPressed: () {
                        // TODO: 实现附件添加功能
                      },
                    ),
                    // 消息输入框
                    Expanded(
                      child: TextField(
                        controller: _messageController,
                        decoration: const InputDecoration(
                          hintText: '输入消息...',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(20)),
                            borderSide: BorderSide.none,
                          ),
                          filled: true,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 8,
                          ),
                        ),
                        maxLines: null,
                        textInputAction: TextInputAction.send,
                        onSubmitted: (_) => _sendMessage(),
                      ),
                    ),
                    // 发送按钮
                    IconButton(
                      icon: const Icon(Icons.send),
                      onPressed: _sendMessage,
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 发送消息方法
  void _sendMessage() {
    final message = _messageController.text.trim();
    if (message.isNotEmpty) {
      final chatStore = Provider.of<ChatStore>(context, listen: false);
      chatStore.sendMessage(message);
      _messageController.clear();

      // 确保滚动到底部
      Future.delayed(const Duration(milliseconds: 100), _scrollToBottom);
    }
  }

  // 构建时间分割线
  Widget _buildTimeDivider(DateTime time) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 16),
      child: Center(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.grey.withOpacity(0.2),
            borderRadius: BorderRadius.circular(10),
          ),
          child: Text(
            _formatTimeDivider(time),
            style: const TextStyle(fontSize: 12, color: Colors.grey),
          ),
        ),
      ),
    );
  }

  // 格式化时间分割线文本
  String _formatTimeDivider(DateTime time) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final messageDate = DateTime(time.year, time.month, time.day);

    if (messageDate == today) {
      return '今天 ${DateFormat('HH:mm').format(time)}';
    } else if (messageDate == yesterday) {
      return '昨天 ${DateFormat('HH:mm').format(time)}';
    } else if (now.difference(messageDate).inDays < 7) {
      return '${DateFormat('EEEE', 'zh_CN').format(time)} ${DateFormat('HH:mm').format(time)}';
    } else {
      return DateFormat('yyyy年MM月dd日 HH:mm').format(time);
    }
  }

  // 判断是否需要显示时间分割线
  bool _shouldShowTimeDivider(DateTime previous, DateTime current) {
    // 如果两条消息间隔超过5分钟，显示时间分割线
    return current.difference(previous).inMinutes > 5;
  }
}

// 消息气泡组件
class MessageBubble extends StatelessWidget {
  final dynamic message; // 消息数据
  final bool isMe; // 是否是自己发送的消息

  const MessageBubble({Key? key, required this.message, required this.isMe})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: isMe
            ? MainAxisAlignment.end
            : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          // 对方头像 (在左侧)
          if (!isMe)
            const CircleAvatar(
              radius: 16,
              backgroundImage: NetworkImage('https://via.placeholder.com/32'),
            ),

          const SizedBox(width: 8),

          // 消息气泡
          Flexible(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              decoration: BoxDecoration(
                color: isMe ? Colors.blue : Colors.grey.shade200,
                borderRadius: BorderRadius.circular(18),
              ),
              child: Text(
                message.content,
                style: TextStyle(
                  color: isMe ? Colors.white : Colors.black87,
                  fontSize: 16,
                ),
              ),
            ),
          ),

          const SizedBox(width: 8),

          // 自己的头像 (在右侧)
          if (isMe)
            const CircleAvatar(
              radius: 16,
              backgroundImage: NetworkImage('https://via.placeholder.com/32'),
            ),
        ],
      ),
    );
  }
}
